package com.gugee.ins.data.task.mark.service;

import com.gugee.ins.common.dal.service.mark.InsMarkBloggerBgsDayDao;
import com.gugee.ins.common.dal.service.mark.InsRkBloggerBgsDayDao;
import com.gugee.ins.common.dto.RankTaskParam;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * ins 带货播主排行表
 * @author huangxin
 */
@Component
@Slf4j
public class InsRkBloggerBgsDaySvc extends AbstractMarkRankProducerHandler {
    /**
     *
     */
    private static final String DATE_FORMATTER = "yyyyMMdd";

    /**
     *
     */
    @Autowired
    InsRkBloggerBgsDayDao insRkBloggerBgsDayDao;

    /**
     *
     */
    @Autowired
    InsMarkBloggerBgsDayDao insMarkBloggerBgsDayDao;

    /**
     * 处理排行表
     */
    @Override
    public void handleRank(RankTaskParam taskParam) {
        // 查找一级分类
        List<String> categoryList = getCategory(taskParam.getCategory(),true);

        long now = getDateTime(taskParam.getDateCode()) / 1000 - 24 * 3600;

        int today = Integer.parseInt(DateTimeUtils.formatSecond(now,DATE_FORMATTER,
                taskConfig.getInsBloggerMarkDaytimeZone()));

        int lastDateCode = Integer.parseInt(DateTimeUtils.formatSecond(now - 24 * 3600,DATE_FORMATTER,
                taskConfig.getInsBloggerMarkDaytimeZone()));

        // 分类的榜单
        if(categoryList != null && !categoryList.isEmpty()){
            for(String category : categoryList){
                markRankDay(today,lastDateCode,category);
            }
        }

        // 删除30天前的无用的日打点数据
        deleteMarkDay(now);
    }

    /**
     *
     * @param dateCode
     * @param category
     */
    public void markRankDay(int dateCode,int lastDateCode,String category){
        try{
            insRkBloggerBgsDayDao.insertRk(dateCode,lastDateCode,category,taskConfig.getInsRkBloggerBgsRankCount());
        }catch (Exception e){
            log.info("ins 带货播主日榜单 生成失败 date:{},category:{},msg:{}", dateCode,category,e.getMessage());
            XxlJobLogger.log("ins 品牌日榜单 生成失败 date:{},category:{},msg:{}",dateCode,category,e.getMessage());
        }
    }

    /**
     * 删除30天前的无用的日打点数据
     */
    public void deleteMarkDay(long now){
        int dateCode = Integer.parseInt(DateTimeUtils.formatSecond(now - 30 * 24 * 3600,DATE_FORMATTER,
                taskConfig.getInsBloggerMarkDaytimeZone()));
        try{
            insMarkBloggerBgsDayDao.deleteByDateCode(dateCode);
        }catch (Exception e){
            log.info("ins 删除带货播主日打点数据失败 date:{},msg:{}", dateCode,e.getMessage());
            XxlJobLogger.log("ins 删除带货播主日打点数据失败 date:{},msg:{}",dateCode,e.getMessage());
        }
    }
}
